#!/usr/bin/env node

/**
 * 清理Vite依赖缓存脚本
 * 用于解决"Outdated Optimize Dep"错误
 */

const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')

const projectRoot = path.resolve(__dirname, '..')
const nodeModulesPath = path.join(projectRoot, 'node_modules')
const viteCachePath = path.join(nodeModulesPath, '.vite')
const distPath = path.join(projectRoot, 'dist')

console.log('🧹 开始清理Vite依赖缓存...')

// 删除.vite缓存目录
if (fs.existsSync(viteCachePath)) {
  console.log('📁 删除 .vite 缓存目录')
  fs.rmSync(viteCachePath, { recursive: true, force: true })
}

// 删除dist目录
if (fs.existsSync(distPath)) {
  console.log('📁 删除 dist 目录')
  fs.rmSync(distPath, { recursive: true, force: true })
}

// 清理npm缓存
try {
  console.log('🗑️  清理npm缓存')
  execSync('npm cache clean --force', { stdio: 'inherit' })
} catch (error) {
  console.warn('⚠️  npm缓存清理失败，继续执行...')
}

// 重新安装依赖
try {
  console.log('📦 重新安装依赖')
  execSync('npm install', { stdio: 'inherit', cwd: projectRoot })
} catch (error) {
  console.error('❌ 依赖安装失败:', error.message)
  process.exit(1)
}

console.log('✅ 清理完成！现在可以重新启动开发服务器')
console.log('💡 运行: npm run dev')